package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import netPacks.message;

public class pinger extends Thread{
    clientConnection clientToPing = null;
    boolean disconFlag = false;
	
	public pinger(clientConnection c){
		this.clientToPing = c;
	}
    
    public synchronized void run(){
    	message ping = new message();
		ping.setAction("ping");
		try {
			ping.setUserId(InetAddress.getLocalHost());
		} 
		catch (UnknownHostException e2) {
			e2.printStackTrace();
		}
    	
		while(!disconFlag){
    		try {
				Thread.sleep(1000);
			}
    		catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Sending ping check...");
    		try {
				this.clientToPing.oos.writeObject(ping);
			} 
    		catch (IOException e) {
    	    	System.err.println("Cannot send ping to client.");
    	    	this.disconFlag = true;
    	    }
    		catch (Exception e2){
    			System.err.println("Unknown exception in client connection.\nClosing connection to: "+clientToPing.getClientId());
    			this.disconFlag = true;
    		}
    	}
		
		if(clientToPing.matched){
    		System.err.println("Exiting pingChecker.");
    		return;
    	}
    	else if(!clientToPing.pingerFailFlag){
    		clientToPing.pingerFailFlag = true;
    		System.err.println("Exiting pingChecker after user removal.");
			return;
		}
		return;
    	}
}
